package com.orangelife.mobile.property.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.JumpManager;
import com.common.util.MoneyUtil2;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.MoneyUtil;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.confirmOrder.biz.ConfirmOrderHttpBiz;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.property.adapter.PropertyBillBaseInfoAdapter;
import com.orangelife.mobile.property.adapter.PropertyBillFeeDetailAdapter;
import com.orangelife.mobile.property.biz.PropertyBiz;
import com.orangelife.mobile.property.biz.PropertyHttpBiz;
import com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper;
import com.orangelife.mobile.voucher.biz.VoucherBiz;
import com.orangelife.mobile.voucher.biz.VoucherHttpBiz;
import com.orangelife.mobile.widget.ScrollListView;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 应缴账单-详情
 *
 * @author wgf
 * @since v3.6.5
 */
public class PropertyBillDetailActivity extends OrangeLifeBaseActivity {

    private static final int WHAT_FEE_DETAIL = 0;
    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.tvTotal)
    TextView tvTotal;
    @Bind(R.id.tvPropertyNum)
    TextView tvPropertyNum;
    @Bind(R.id.tvYuan)
    TextView tvYuan;
    @Bind(R.id.tvTip)
    TextView tvTip;
    @Bind(R.id.lvPropertyBillBaseInfo)
    ScrollListView lvPropertyBillBaseInfo;
    @Bind(R.id.lvPropertyBillBaseInfoInNoBill)
    ScrollListView lvPropertyBillBaseInfoInNoBill;
    @Bind(R.id.lvPropertyBillOrderInfo)
    ScrollListView lvPropertyBillOrderInfo;
    @Bind(R.id.btPayCost)
    Button btPayCost;
    @Bind(R.id.tvIsPay)
    TextView tvIsPay;
    //    @Bind(R.id.tvRealCost)
//    TextView tvRealCost;
    @Bind(R.id.swipeRefreshLayout2)
    SwipeRefreshLayout swipeRefreshLayout2;
    @Bind(R.id.llNoBill)
    LinearLayout llNoBill;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    /** 总金额 */
    @Bind(R.id.tvAmountPaid)
    TextView tvAmountPaid;
    /** 可抵扣金额 */
    @Bind(R.id.tvDeductionMoney)
    TextView tvDeductionMoney;
    /** 抵用券抵扣金额 */
    @Bind(R.id.tvVoucherMoney)
    TextView tvVoucherMoney;
    /** 抵用券金额 */
    @Bind(R.id.tvVoucherInfo)
    TextView tvVoucherInfo;

    private List<Map<String, Object>> baseInfo;
    private List<Map<String, Object>> orderInfo;
    private PropertyBillBaseInfoAdapter mBaseInfoAdapter;
    private PropertyBillBaseInfoAdapter mBaseInfoAdapter2;
    private PropertyBillFeeDetailAdapter mOrderInfoAdapter;
    /** 提示语 */
    private String tip;
    private String feetip;
    /** 房号 */
    private String apartmentID;
    /** 小区ID */
    private String commID;
    /** 0:不检查是否存在关联信息,1:检查是否存在关联信息 */
    private String mType = "";
    /** 房屋可抵扣金额 */
    private String mDeductionMoney = "0.00";
    /** 实付金额 */
    private String mAmountPaid = "0.00";
    /** 应缴总金额 */
    private String mTotalAmount = "0.00";
    /** 抵用券金额 */
    private String mVoucherMoney = "0.00";
    /** 用于计算抵用券最高金额的 */
    private String forVoucherMoney = "0.00";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_property_bill_detail);
        ButterKnife.bind(this);
        getIntentInfo();
        initView();
        requestPropertyBillDetail();
        setListener();
    }

    private void getIntentInfo() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            apartmentID = bundle.getString("apartmentID");
            commID = bundle.getString("commID");
            mType = bundle.getString("type");
        }
    }

    private void initView() {
        tvTitle.setText("应缴账单");
        ivTitleRight.setVisibility(View.INVISIBLE);
        baseInfo = new ArrayList<>();
        orderInfo = new ArrayList<>();
    }

    /** 实缴金额 . 实缴金额=已选总金额-可抵扣金额（可抵扣金额不会变，请求到总金额来一次，请求到可抵扣来一次，改变总金额来一次） */
    private void setAmountPaid() {
        String s1 = DecimalUtil.add(mVoucherMoney, mDeductionMoney);
        String s2 = DecimalUtil.subtract(s1, mTotalAmount);
        if (Float.parseFloat(s2) > 0) {//
            mAmountPaid = "0.00";
        } else {
            mAmountPaid = DecimalUtil.subtract(DecimalUtil.subtract(mTotalAmount, mDeductionMoney), mVoucherMoney);
        }
        tvAmountPaid.setText(Html.fromHtml("实缴金额：<font color=\"#fea00f\">" + Constant.RMB_FLAG + MoneyUtil.handleMoney(mAmountPaid) + "</font>"));
    }

    /** 已选年份的总缴费金额 */
    private void setTotalAmount() {
        tvPropertyNum.setText(MoneyUtil.handleMoney(mTotalAmount));
    }

    /** 设置实际抵扣余额 */
    private void setDeductionShow() {
        /*展示用抵扣金额，抵扣金额为负，显示正数；抵扣金额为正，上限是（订单总额-抵用券） */
        String deductionShow;
        String trueTotalAmountAfterVoucher = DecimalUtil.subtract(mTotalAmount, mVoucherMoney);
        if (trueTotalAmountAfterVoucher.contains("-")) {//总额被抵用券抵消掉
            trueTotalAmountAfterVoucher = "0.00";
        }

        String trueTotalAmountAfterDeduction = DecimalUtil.subtract(trueTotalAmountAfterVoucher, mDeductionMoney);//实际总额-余额，如果是负的，说明余额大于总额

        if (!mDeductionMoney.contains("-") && trueTotalAmountAfterDeduction.contains("-")) {//如果余额是正的，且大于总额（总额是会变化的，假如余额少了，就要重新判断一下），则等于总额；
            deductionShow = trueTotalAmountAfterVoucher;//减去抵用券的总额（上限）
        } else {
            deductionShow = mDeductionMoney;//全部余额
        }
        //余额，是不会变的；
        setFlagMoney(deductionShow, tvDeductionMoney);
    }

    private void setListener() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPropertyBillDetail();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestPropertyBillDetail();
            }
        });
        swipeRefreshLayout2.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestPropertyBillDetail();
            }
        });
    }

    private void showNoBillView() {
        swipeRefreshLayout2.setVisibility(View.VISIBLE);
    }

    private void hideNoBillView() {
        swipeRefreshLayout2.setVisibility(View.GONE);
    }

    /** 查询房屋可抵扣金额 */
    private void requestDeductionMoney() {
        showDialog();
        PropertyHttpBiz.getDeductionMoney(commID, apartmentID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                String money = PropertyHttpBiz.handleDeductionMoney(jsonObject);
                if (money != null) {
                    mDeductionMoney = MoneyUtil2.handleMoney(money, true);
                    setDeductionShow();
                    calcForVoucherMoneyWithDeductionMoney();//如果是负的，需要重新计算给抵用券用的总额（提高总额）
                    setAmountPaid();//重新计算实缴金额
                    requestVoucherHighestPrice();//请求默认抵用券
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NODATA);
                }
            }
        });
    }

    private void setForVoucherMoneyFromTotal() {
        forVoucherMoney = mTotalAmount;
    }

    private void calcForVoucherMoneyWithDeductionMoney() {
        if (mDeductionMoney.contains("-")) {//表示是账单余额是负的
            forVoucherMoney = DecimalUtil.subtract(mTotalAmount, mDeductionMoney);//总额+负的余额，使账单欠费总额得以提高，抵用券的门槛；
        }
    }

    /** 获取我的物业缴费信息 */
    private void requestPropertyBillDetail() {
        PropertyHttpBiz.getFeeDetail(commID, apartmentID, mType, mHandler, WHAT_FEE_DETAIL);
    }

    private void handleFeeDetail(Map<String, Object> map) {//第一次初始化，获得缴费总金额
        if (map != null) {
            emptyLayout.dismiss();
            tip = "缴费月份仅限从欠费开始时间起连月选择，暂不支持跨月选择";
            feetip = "是否确认缴费？";
            mTotalAmount = String.valueOf(map.get("totalamount"));
            apartmentID = String.valueOf(map.get("apartmentID"));
            setData();
            setTotalAmount();
            baseInfo = (List<Map<String, Object>>) map.get("baseInfo");
            setBaseInfoAdapter();
            orderInfo = (List<Map<String, Object>>) map.get("orderInfo");
            addParamToOrderInfo();
            if (orderInfo != null && orderInfo.size() != 0) {
                hideNoBillView();
                setOrderInfoAdapter();
            } else {
                showNoBillView();
            }
            setForVoucherMoneyFromTotal();//初始化抵用券需要的总额，如果余额是负的，需要加上
            requestDeductionMoney();//请求余额；
        } else {
            emptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }

    private void addParamToOrderInfo() {//默认是所有全部年份被勾选 1 全选 2 全不选 3 半选
        for (int i = 0; i < orderInfo.size(); i++) {
            List<HashMap<String, Object>> monthList = (List<HashMap<String, Object>>) orderInfo.get(i).get("yearInfo");
            LinkedList<String> ids = new LinkedList<>();
            for (int j = 0; j < monthList.size(); j++) {
                List<String> feeDetailIDs = (List<String>) monthList.get(j).get("feeDetailIDs");
                for (int k = 0; k < feeDetailIDs.size(); k++) {
                    ids.add(feeDetailIDs.get(k));
                }
            }
            orderInfo.get(i).put("selectedIds", ids);

            orderInfo.get(i).put("yearStatus", "1");
            String yearSelectedInfo;
            List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) orderInfo.get(i).get("yearInfo");
            StringBuffer sb = new StringBuffer();
            String firstMonth = "";
            String tailMonth = "";
            for (int j = 0; j < list.size(); j++) {
                String month = (String) list.get(j).get("month");
                sb.append(month);
                if (j < list.size() - 1) {
                    sb.append(",");
                }//头尾
                if (j == 0) {
                    firstMonth = month;
                } else {
                    tailMonth = month;
                }
            }
            yearSelectedInfo = PropertyBiz.getSelectedYearInfo(firstMonth, tailMonth);
            orderInfo.get(i).put("yearSelectedInfo", yearSelectedInfo);
            orderInfo.get(i).put("selectedMonth", sb.toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        Bundle bundle = data.getExtras();
        if (resultCode == 1) {//抵用券返回
            handleJumpBackVoucher();
        }
        if (bundle == null) {
            return;
        }
        if (resultCode == 0) {//选择要缴月份返回
            int pos = bundle.getInt("position");
            String yearSelectedInfo = bundle.getString("yearSelectedInfo");
            String yearStatus = bundle.getString("yearStatus");
            String ytotal = bundle.getString("ytotal");
            String selectedMonth = bundle.getString("selectedMonth");
            ArrayList<String> selectedIds = (ArrayList<String>) bundle.getSerializable("selectedIds");

            orderInfo.get(pos).put("yearSelectedInfo", yearSelectedInfo);
            orderInfo.get(pos).put("yearStatus", yearStatus);
            orderInfo.get(pos).put("ytotal", ytotal);
            orderInfo.get(pos).put("selectedMonth", selectedMonth);
            orderInfo.get(pos).put("selectedIds", selectedIds);
            mTotalAmount = "0";//重新计算总金额 for ytotal add m
            for (int i = 0; i < orderInfo.size(); i++) {
                String ytotal2 = (String) orderInfo.get(i).get("ytotal");
                mTotalAmount = DecimalUtil.add(mTotalAmount, ytotal2);
            }
            setForVoucherMoneyFromTotal();
            requestVoucherHighestPrice();//总额变了，重新请求最高抵用券
            setTotalAmount();//设置总额
            setAmountPaid();//设置实缴金额
            setDeductionShow();//设置实际抵扣余额
            mOrderInfoAdapter.setList(orderInfo);
            mOrderInfoAdapter.notifyDataSetChanged();
        }
    }

    /** 立即缴费，生成订单，获得订单流水号 */
    private void requestGenOrder() {

        List<String> feeDetailIDS = getFeeDetailIDs();

        if (feeDetailIDS == null || feeDetailIDS.size() == 0) {

            ToastHelper.getInstance()._toast("至少选择一条月份账单");
            return;
        }
        showDialog();
        ArrayList<String> voucherIDs = new ArrayList<>();
        if (!StringUtil.isBlank(voucherID)) {
            voucherIDs.add(voucherID);
        }
        //生成订单
        ConfirmOrderHttpBiz.genOrder(commID, apartmentID, feeDetailIDS, voucherIDs, mDeductionMoney, mTotalAmount, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                closeDialog();
                /*成功之后，会跳转到支付界面*/
                ConfirmOrderHttpBiz.handleGenOrder(PropertyBillDetailActivity.this, response, mAmountPaid);
            }
        });
    }

    public List<String> getFeeDetailIDs() {
        LinkedList<String> list = new LinkedList<>();
        for (int i = 0; i < orderInfo.size(); i++) {
            List<String> selectedIds = (List<String>) orderInfo.get(i).get("selectedIds");
            if (selectedIds != null) {
                for (int j = 0; j < selectedIds.size(); j++) {
                    String id = selectedIds.get(j);
                    list.add(id);
                }
            }
        }
        return list;
    }

    private void showNoService() {
        emptyLayout.setErrorMessage("该房屋未开通服务");
        emptyLayout.setErrorType(EmptyLayout.NODATA);
    }

    private FeeHandler mHandler = new FeeHandler(this);

    private static class FeeHandler extends Handler {//非静态内部类会隐式持有外部类的引用，导致内存泄露，所以使用静态内部类
        private WeakReference<PropertyBillDetailActivity> mAct = null;

        FeeHandler(PropertyBillDetailActivity act) {
            mAct = new WeakReference<>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            PropertyBillDetailActivity act = mAct.get();
            if (act != null) {
                Object result = msg.obj;
                switch (msg.what) {
                    case WHAT_FEE_DETAIL:
                        act.dismissProgress();
                        int code = OrangeErrorHandler.getInstance().getHttpErrorCode(result, "", "");
                        if (code == 100009) {
                            act.showNoService();
                        } else {
                            Map<String, Object> map = PropertyHttpBiz.handleFeeDetail(result);
                            act.handleFeeDetail(map);
                        }
                        break;
                }
            }
        }
    }

    private void dismissProgress() {
        emptyLayout.dismiss();
        swipeRefreshLayout.setRefreshing(false);
        swipeRefreshLayout2.setRefreshing(false);
    }

    /**
     * 设置界面上的账单信息
     */
    private void setData() {
        tvTip.setText(tip);
    }

    /**
     * 设置账单条目的信息
     */
    private void setBaseInfoAdapter() {
        mBaseInfoAdapter = new PropertyBillBaseInfoAdapter(PropertyBillDetailActivity.this, baseInfo);
        lvPropertyBillBaseInfo.setAdapter(mBaseInfoAdapter);
        mBaseInfoAdapter2 = new PropertyBillBaseInfoAdapter(PropertyBillDetailActivity.this, baseInfo);
        lvPropertyBillBaseInfoInNoBill.setAdapter(mBaseInfoAdapter2);
    }

    /**
     * 设置账单条目的信息
     */
    private void setOrderInfoAdapter() {
        mOrderInfoAdapter = new PropertyBillFeeDetailAdapter(PropertyBillDetailActivity.this, orderInfo);
        lvPropertyBillOrderInfo.setAdapter(mOrderInfoAdapter);
    }

    private String voucherInfo = VoucherBiz.STR_NO_VOUCHER;
    private String voucherID;


    /**
     * 跳转到抵用券列表
     */
    private void jumpToVoucherList() {
        if (VoucherBiz.hasVoucher(voucherInfo, true)) {
            VoucherHttpBiz.cancelVoucherHighestPriceList();/*为了避免进入抵用券列表，选中抵用券后，原先最高金额抵用券的值才返回来的情况出现，如果超时没回来，就取消请求*/
            SelectedVoucherIDListHelper.getInstance().setVoucherListMapKey(apartmentID);
            JumpManager.jumpToVoucherListWithGood(this, VoucherHttpBiz.TYPE_PROPERTY, commID, apartmentID, mTotalAmount);
        }
    }

    private void requestVoucherHighestPrice() {
        VoucherHttpBiz.getVoucherHighestPriceListWithGood(commID, apartmentID, forVoucherMoney, VoucherHttpBiz.TYPE_PROPERTY, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                List<Map<String, Object>> highestPriceVoucherList = VoucherHttpBiz.handleVoucherHighestPriceList(response);
                if (highestPriceVoucherList != null && highestPriceVoucherList.size() > 0) {
                    mVoucherMoney = String.valueOf(highestPriceVoucherList.get(0).get("money"));
                    mVoucherMoney = MoneyUtil2.handleMoney(mVoucherMoney, true);
                    voucherID = String.valueOf(highestPriceVoucherList.get(0).get("couponID"));
                    SelectedVoucherIDListHelper.getInstance().addSelectedVoucherID(voucherID, apartmentID, true);
                    if (!StringUtil.isBlank(mVoucherMoney)) {/*默认是暂无，而暂无也点不进去，所以不需要处理无值的情况*/
                        voucherInfo = mVoucherMoney + "元抵用券";
                    }
                    setFlagMoney(mVoucherMoney, tvVoucherMoney);
                    VoucherBiz.setVoucherInfoBackground(tvVoucherInfo, voucherInfo, PropertyBillDetailActivity.this);
                    setAmountPaid();//请求抵用券之后，重新设置实缴金额
                    setDeductionShow();//重新设置展示余额；
                }
            }
        });
    }

    private void setFlagMoney(String outMoney, TextView tv) {
        if (StringUtil.isBlank(outMoney)) {
            return;
        }
        String money = outMoney;
        if (money.contains("-")) {
            money = money.substring(1, money.length());
            money = "+" + money;
        } else if (!money.equals("0.00")) {
            money = "-" + money;
        }
        tv.setText(money + "元");
    }


    private void handleJumpBackVoucher() {
        /*唯一有用的，其实只是抵用券ID而已*/
        ArrayList<String> voucherIDList = SelectedVoucherIDListHelper.getInstance().getSelfVoucherList();
        if (voucherIDList != null && voucherIDList.size() == 1) {
            voucherID = voucherIDList.get(0);
        } else {
            voucherID = "";
        }
        mVoucherMoney = SelectedVoucherIDListHelper.getInstance().getTotalSelectedVoucherPrice();
        mVoucherMoney = MoneyUtil2.handleMoney(mVoucherMoney, true);
        setFlagMoney(mVoucherMoney, tvVoucherMoney);
        String newVoucherInfo = VoucherBiz.getVoucherInfo(voucherInfo);/*选中抵用券之后，处理抵用券信息可调用此方法*/
        VoucherBiz.setVoucherInfoBackground(tvVoucherInfo, newVoucherInfo, this);
        setAmountPaid();//更换抵用券之后，重新设置实缴金额
        setDeductionShow();
    }

    @OnClick({R.id.btPayCost, R.id.iv_title_right, R.id.llVoucher})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btPayCost:
                requestGenOrder();
                break;
            case R.id.iv_title_right:
                break;
            case R.id.llVoucher:
                jumpToVoucherList();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*如果没有进入支付界面，则在关闭此界面时，将前一个列表PropertyBillHouseListActivity从中删除*/
        ExitApplication.getInstance().clearPaidActivityList();
        mHandler.removeCallbacksAndMessages(null);//在销毁Activity的时候，将Handler的Message列表全部清空
        SelectedVoucherIDListHelper.getInstance().destroyBiz();
    }

}
